import random
import string
import time

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render, redirect
from django.urls import reverse

from commodity.models import CommodityInfos
from shopper.form import LoginForm, LoginModelForm
from shopper.models import OrderInfos, CartInfos
from shopper.pays import get_pay


# Create your views here.
@login_required(login_url='shopper/login.html')
def shopperView(request):
    title='个人中心'
    classContent='informations'
    t=request.GET.get('t','')
    p=request.GET.get('p',1)
    payTime=request.session.get('payTime','')
    if t and payTime and t==payTime:
        payInfo=request.session.get('payInfo','')
        OrderInfos.objects.create(**payInfo)
        del request.session['payInfo']
        del request.session['payTime']
    orderInfos=OrderInfos.objects.filter(user_id=request.user.id).order_by('-created')
    paginator = Paginator(orderInfos, 7)
    try:
        pages=paginator.page(p)
    except PageNotAnInteger:
        pages=paginator.page(1)
    except EmptyPage:
        pages=paginator.page(paginator.num_pages)
    return render(request,'shopper.html',locals())

def loginView(request):
    """
    用户登录视图函数，处理用户登录请求，
    支持现有用户认证和新用户注册
    """
    # 定义变量title和classContent用于设置公用模板base.html的模板变量
    title = "用户登录"
    classContent = "logins"
    # 对用户的请求方式进行判断
    if request.method == "POST":
        # 实例化登录模型并绑定POST数据
        # infos = LoginForm(data= request.POST)
        infos = LoginModelForm(data=request.POST)
        # 验证表单字段的数据是否正确
        # if infos.is_valid():
        data = infos.data
        # 如果是POST请求，那么视图函数会执行注册和登录操作
        # 获取请求参数username和password
        username = data['username']
        password = data['password']
        # 查询username的数据是否存在于内置模型User
        if User.objects.filter(username=username):
            # 验证账号和密码是否与模型User中对应的一致
            user = authenticate(username=username, password=password)
            # 如果通过验证，使用内置函数login执行登录操作，登录成功后
            # 跳转到个人中心页面
            if user:
                login(request, user)
                return redirect(reverse('shopper:shopper'))
        else:
            # username不存在于内置模型User，执行注册
            state = "注册成功"
            d = dict(username=username, password=password, is_staff=1, is_active=1)
            user = User.objects.create_user(**d)
            user.save()
    # else:
    #     # 获取错误信息，并以JSON格式输出
    #     error_msg = infos.errors.as_json()
    #     print(error_msg)

    else:
        # 处理HTTP的GET请求
        # infos = LoginForm()
        infos = LoginModelForm()
    return render(request, 'login.html', locals())


def logoutView(request):
    logout(request)
    return redirect(reverse('index:index'))

def shopcartView(request):
    title = '我的购物车'
    classContent = 'shopcarts'
    userId = request.user.id
    id = request.GET.get('id')
    quantity = request.GET.get('quantity', 1)
    if id:
        CartInfos.objects.update_or_create(
            commodityInfos_id=id,
            user_id=userId,
            defaults={'quantity': quantity},
        )
        return redirect('shopper:shopcart')
    getUserId = CartInfos.objects.filter(user_id=userId)
    commodityDict = {x.commodityInfos_id: x.quantity for x in getUserId}
    commodityInfos = CommodityInfos.objects.filter(id__in=commodityDict.keys())
    return render(request, 'shopcart.html', locals())


def deleteAPI(request):
    result={'state':'success'}
    userId=request.GET.get('userId','')
    commodiyId=request.GET.get('commodiyId','')
    if userId :
        CartInfos.objects.filter(user_id=userId).delete()
    elif commodiyId :
        CartInfos.objects.filter(commodityInfos_id=commodiyId).delete()
    else:
        result={'state':'fail'}
    return JsonResponse(result)

def paysView(request):
    total = request.GET.get('total',0)
    total = total.replace('￥','')
    try:
        total =float(total)
    except ValueError:
        return redirect('shopper:shopcart')
    if total > 0:
        timestamp = int(time.time()*1000)
        random_str="".join(random.choice(string.digits,k=6))
        out_trade_no=f"{timestamp}{random_str}"
        total_amount="{0:.2f}".format(total)
        payInfo=dict(price=total,user_id=request.user.id,state='已支付')
        request.session['payInfo']=payInfo
        request.session['payTime']=out_trade_no
        domain='http://'+request.get_host()
        return_url=f"{domain}/shopper/pay_callback"
        print(f"out_trade_no:{out_trade_no},type:{type(out_trade_no)}")
        print(f"total_amount:{total_amount},type:{type(total_amount)}")
        print(f"return_url:{return_url},type:{type(return_url)}")
        url=get_pay(out_trade_no,total_amount,return_url)
        print(f"支付宝支付链接:{url}")
        if url:
            return redirect(url)
        else:
            return redirect('shopper:shopcart')
    else:
        return redirect('shopper:shopcart')

def paycallbackView(request):
        payTime=request.session['payTime']
        if payTime:
            payInfo=request.session['payInfo']
            if payInfo:
                OrderInfos.objects.create(**payInfo)
                del request.session['payTime']
                del request.session['payInfo']

        return redirect(reverse('shopper:shopper'))
